import json
import logging
import traceback
from datetime import datetime
from django.db import transaction
from django.http import JsonResponse
from rest_framework import status
from Model.models import User as U, Role, Page, Operation
from Model.modelsView import UserInfo
from tools.Tools import encryptPassword, token_username, check_text, createHandleLog, getCurrentUser

logger_info = logging.getLogger('info')
res = dict()


def User(request):
    res.clear()
    try:
        if request.method == 'GET':
            return queryUser(request)
        elif request.method == 'POST':
            return createUser(request)
        elif request.method == 'PUT':
            return modifyUser(request)
        elif request.method == 'DELETE':
            return delUser(request)
    except Exception as e:
        print(e)
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 200
        res['message'] = '请求错误!'
        return JsonResponse(res, status=status.HTTP_400_BAD_REQUEST)


def OneUser(request):
    res.clear()
    try:
        if request.method == 'GET':
            return getUser(request)
        elif request.method == 'POST':
            pass
        elif request.method == 'PUT':
            pass
        elif request.method == 'DELETE':
            pass
    except Exception as e:
        print(e)
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 200
        res['message'] = '请求错误!'
        return JsonResponse(res, status=status.HTTP_400_BAD_REQUEST)


# 获取单一用户信息
def getUser(request):
    token = request.META.get('HTTP_AUTHORIZATION')
    try:
        name = token_username[token]
        pages = []
        operations = []
        username = ''
        avatar = ''
        if name == 'superAdmin':
            page = Page.objects.all()
            operation = Operation.objects.all()
            pages = [str(i.page_id) for i in page]
            operations = [str(i.operation_id) for i in operation]
            username = '超级管理员'
            avatar = 'https://joeschmoe.io/api/v1/jia'
        else:
            if name.find("@") == -1:
                userInfo = U.objects.get(telephone=name)
            else:
                userInfo = U.objects.get(email=name)
            roles = userInfo.role

            for i in roles.split(","):
                role = Role.objects.get(role_id=i)
                pages += role.page_auth.split(',')
                operations += role.operation_auth.split(',')
            pages = list(set(pages))
            operations = list(set(operations))
            username = userInfo.user_name
            avatar = userInfo.avatar
        data = {'username': username, 'page': pages,
                'operation': operations, 'avatar': avatar}
        res['status'] = 200
        res['data'] = data
        res['message'] = '请求成功'
        return JsonResponse(res, status=status.HTTP_200_OK)
    except:
        res['status'] = 401
        res['message'] = '暂无权限'
        return JsonResponse(res, status=status.HTTP_401_UNAUTHORIZED)


# 获取用户信息
def queryUser(request):
    user_name = request.GET.get('user_name')
    real_name = request.GET.get('real_name')
    telephone = request.GET.get('telephone')
    userInfo = UserInfo.objects.all()
    if check_text(user_name):
        userInfo = userInfo.filter(user_name__contains=user_name)
    if check_text(real_name):
        userInfo = userInfo.filter(real_name__contains=real_name)
    if check_text(telephone):
        userInfo = userInfo.filter(telephone=telephone)
    res['status'] = 200
    res['data'] = list(userInfo.values())
    res['message'] = '请求成功'
    return JsonResponse(res, status=status.HTTP_200_OK)


# 新建用户
@transaction.atomic
def createUser(request):
    body = json.loads(request.body)
    user_name = body.get('user_name')
    real_name = body.get('real_name')
    telephone = body.get('telephone')
    email = body.get('email')
    role = body.get('role')
    avatar = body.get('avatar')
    user = U.objects.create()
    user.user_id = user.id
    user.user_name = user_name
    user.real_name = real_name
    user.telephone = telephone
    user.email = email
    user.role = role
    user.avatar = avatar
    user.password = encryptPassword(telephone)
    createHandleLog('新增用户', str(getCurrentUser(request)), body)
    logger_info.info(f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《新增用户》权限 新增内容 {body}')
    user.save()
    res['status'] = 200
    res['message'] = '新建成功'
    return JsonResponse(res, status=status.HTTP_200_OK)


# 修改用户
def modifyUser(request):
    body = json.loads(request.body)
    user_id = body.get('user_id')
    user_name = body.get('user_name')
    real_name = body.get('real_name')
    telephone = body.get('telephone')
    email = body.get('email')
    role = body.get('role')
    avatar = body.get('avatar')
    user = U.objects.get(user_id=user_id)
    user.user_name = user_name
    user.real_name = real_name
    user.telephone = telephone
    user.email = email
    user.role = role
    if check_text(avatar):
        user.avatar = avatar
    createHandleLog('修改用户', str(getCurrentUser(request)), body)
    logger_info.info(f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《修改用户》权限 新增内容 {body}')
    user.save()
    res['status'] = 200
    res['message'] = '修改成功'
    return JsonResponse(res, status=status.HTTP_200_OK)


# 删除用户
def delUser(request):
    user_id = request.GET.get('user_id')
    user = U.objects.get(user_id=user_id)
    createHandleLog('删除用户', str(getCurrentUser(request)), user.real_name)
    logger_info.info(f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《删除用户》权限 删除 {user.real_name}')
    user.delete()
    res['status'] = 200
    res['message'] = '删除成功'
    return JsonResponse(res, status=status.HTTP_200_OK)
